<?php
namespace app\api\controller\deerhome\user;

use app\api\controller\deerhome\user\Base;
use think\Db;
use think\Log;
use app\admin\model\deerhome\Order as OrderModel;
/**
 * 微信支付回调
*/
class Notify extends Base
{
    public function index()
    {
        $_order_payed=false;
        $order_sn=$this->request->param("sn",'');
        $notifyCon=\WeChat\Contracts\Tools::getRawInput();
        if($notifyCon){
            Log::write('【微信支付回调】：'.json_encode($notifyCon));
        }
      
        if($order_sn=="" && $notifyCon=="" ){
            Log::error('【微信支付回调】订单号为空，且没有post数据');
            return;
        }
        $order=[];
        Db::startTrans();
        try {
            $config=$this->getWeixinConfig();
            $payment = \WePayV3\Order::instance($config);
            if($order_sn==""){
                $data = $payment->notify();
                $result=\json_decode($data['result'],true);
                $order_sn=$result['out_trade_no'];
            }
            $order_sn_mask=\explode("S",$order_sn);
            if(count($order_sn_mask)!=2){
                throw new \Exception("订单号格式不正确");
            }
            $order_sn_father=$order_sn_mask[0];
            $sub_order_id=(int)$order_sn_mask[1];
            $order=Db::name("deerhome_order")->field("id,jz_items_id,num,sn,status,price_need_pay,price_payed,agent_lev1_percent,agent_lev2_percent,order_way,order_type")->where("sn",$order_sn_father)->find();
            if(!$order){
                throw new \Exception("订单不存在");
            }
            if($order['status']>5){
                throw new \Exception("该订单状态不可支付");
            }
            $need_pay=bcsub($order['price_need_pay'],$order['price_payed'],2);
            $need_pay=$need_pay*100;
            $orderQuery=$payment->query($order_sn);
            if(!isset($orderQuery['trade_state'])){
                throw new \Exception("订单查询失败:".$orderQuery['message']);
            }
            if($orderQuery['trade_state']=="SUCCESS" ){
                if($orderQuery['amount']['payer_total']!=$need_pay){
                    throw new \Exception("订单支付金额不正确，应支付￥{$need_pay}分，实际支付￥{$orderQuery['amount']['payer_total']}分");
                }
            }else{
                throw new \Exception("订单交易状态[{$orderQuery['trade_state']}]");
            }
            $log_txt="补差价￥".($need_pay/100)."元，支付成功";
            $pay_time=date("Y-m-d H:i:s",strtotime($orderQuery['success_time']));
            $upateOrder=[];
            $upateOrder['price_payed']=bcadd($order['price_payed'],$need_pay/100,2);
            if($order['price_payed']==0){
                $upateOrder['status']=2;
                $log_txt="支付成功，等待派单";
                Db::name("deerhome_items")->where("id",$order['jz_items_id'])->setInc("sale_times",$order['num']);
                if($order['order_type']==1 && $order['order_way']==2){
                    $upateOrder['status']=3;
                    $upateOrder['hx_code']=(new OrderModel)->createCode();
                    $log_txt="支付成功，请按时到门店服务";
                }
                if($order['order_type']==2){
                    $log_txt="支付成功，等待发货";
                }
            }

            //更新分佣
            if($order['agent_lev1_percent']>0){
                $upateOrder['agent_lev1_price']=bcdiv(bcmul($order['price_need_pay'],$order['agent_lev1_percent'],2),100,2);
            }
            if($order['agent_lev2_percent']>0){
                $upateOrder['agent_lev2_price']=bcdiv(bcmul($order['price_need_pay'],$order['agent_lev2_percent'],2),100,2);
            }

            Db::name("deerhome_order")->where("sn",$order_sn_father)->update($upateOrder);
            Db::name("deerhome_order_pay_log")->where("id",$sub_order_id)->where("order_sn",$order_sn_father)->update([
                'pay_time'=>$pay_time,
                'status'=>2,
                'pay_way'=>'微信支付',
                'payway_type'=>1
            ]);
            
            Db::name("deerhome_order_log")->insert(["order_id"=>$order['id'],"ac_user"=>"用户","note"=>$log_txt,"add_time"=>date("Y-m-d H:i:s")]);

            //短信通知
            $controller = '\app\api\controller\deerhome\user\Demo';
            $objCon = new $controller;
            call_user_func_array(array($objCon,'smsSend'),array(['uptime'=>time(),'orderid'=>$order['id']]));
            //短信通知

            Db::commit();
            echo '{"code","SUCCESS","msg":"OK"}}';
        } catch (\Exception $e) {
            echo '{"code","FAIL","msg":"'.$e->getLine()."|".$e->getMessage().'"}}';
            Log::error('【微信支付回调】'.$order_sn.'错误信息:'.$e->getLine()."|".$e->getMessage() );
        }
        return;
    }
}
?>